package com.woniuxy.project115.kaer.tenant.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.project115.kaer.tenant.entity.OrderEvaluate;
import com.woniuxy.project115.kaer.tenant.entity.OrderLog;
import com.woniuxy.project115.kaer.tenant.entity.ServiceOrder;
import com.woniuxy.project115.kaer.tenant.mapper.OrderEvaluateMapper;
import com.woniuxy.project115.kaer.tenant.mapper.OrderLogMapper;
import com.woniuxy.project115.kaer.tenant.mapper.ServiceOrderMapper;
import com.woniuxy.project115.kaer.tenant.param.EvaluateOrderParam;
import com.woniuxy.project115.kaer.tenant.service.OrderEvaluateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.project115.kaer.tenant.util.Data;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuH
 * @since 2025年02月18日
 */
@Service
public class OrderEvaluateServiceImpl extends ServiceImpl<OrderEvaluateMapper, OrderEvaluate> implements OrderEvaluateService {
    @Resource
    private OrderEvaluateMapper orderEvaluateMapper;

    @Resource
    private ServiceOrderMapper serviceOrderMapper;

    @Resource
    private OrderLogMapper orderLogMapper;

    @Override
    public void evaluate(EvaluateOrderParam param, Integer userId, String userName) throws Exception {
        ServiceOrder serviceOrder = serviceOrderMapper.selectById(param.getOrderNum());
        if (serviceOrder == null) {
            throw new Exception("订单不存在");
        }
        if (serviceOrder.getState() != Data.SERVICE_ORDER_WAIT_EVALUATE) {
            throw new Exception("订单状态异常");
        }
        if (serviceOrder.getUserId() != userId) {
            throw new Exception("订单不属于该用户");
        }
        OrderEvaluate evaluate = BeanUtil.toBean(param, OrderEvaluate.class);
        evaluate.setEvaluatorId(userId)
                .setEvaluatorName(userName)
                .setEvaluateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")))
                .setStoreId(serviceOrder.getStoreId())
                .setCommentId(0)
                .setState(0);
        orderEvaluateMapper.insert(evaluate);

        serviceOrder.setState(Data.SERVICE_ORDER_COMPLETED);
        serviceOrderMapper.updateById(serviceOrder);

        //更新订单日志
        orderLogMapper.insert(
                new OrderLog()
                        .setOperator("用户")
                        .setServiceOrderNum(param.getOrderNum())
                        .setOperateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")))
                        .setOperateType("用户评价")
        );

    }
}
